/**
 * @FileName: VnetReportController.java
 * @Author
 * @Description:
 * @Date 2016年9月1日 上午10:34:22
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Page;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.VnetRecord;
import cn.hpclub.server.service.VnetService;
import cn.hpclub.server.util.ExcelLargeDataUtils;
import cn.hpclub.server.util.SystemConfigUtil;

public class VnetReportController extends BaseAdminController<VnetRecord>{
    private static final String ORG_LIST = "orgList";
    private static final String ORG_ID   = "org_id";
    private static final String V_GROUP_TYPE   = "vgrouptype";
    private static Logger       logger   = LoggerFactory.getLogger(VnetReportController.class);

    public void list(){
        String isExport = getPara("isExport");

        int defaultOrgId = initOrgTree();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(searchInfo.get(ORG_ID) == null){
            searchInfo.put(ORG_ID, String.valueOf(defaultOrgId));
        }
        if (searchInfo.get(V_GROUP_TYPE) == null) {
        	searchInfo.put(V_GROUP_TYPE, "0");
        }

        if("1".equals(isExport)){
            export(searchInfo);
        } else{
            query(searchInfo);
        }
    }

    /*
     * private int initOrgTree(){ List<Entry<String, String>> orgList =
     * InterfaceUtil.getOrgList(); setAttr(ORG_LIST, orgList); if(orgList.size()
     * > 0){ return Integer.parseInt(orgList.get(0).getValue()); } else{ return
     * 0; } }
     */

    private void query(ConcurrentHashMap<String, String> searchInfo){
        getPage(searchInfo);
        setAttrs(searchInfo);
        render("/admin/vnet_report_list.tpl");
    }

    @SuppressWarnings("static-access")
    private void getPage(ConcurrentHashMap<String, String> searchInfo){
        String select = VnetService.getSelectSql();

        String sqlExceptSelect = VnetService.service.getSqlExceptSelect(searchInfo);
        int pageNumber = getParaToInt("pageNumber", 1);
        Page<VnetRecord> pager = VnetRecord.dao.paginate(pageNumber, getParaToInt("pageSize", 10), select,
                                                         sqlExceptSelect);
        /* 删除最后一页所有数据后，显示最后一页前一页 */
        if(pager.getPageNumber() > 1 && pager.getList().size() == 0){
            pager = VnetRecord.dao.paginate(pageNumber - 1, getParaToInt("pageSize", 10), select, sqlExceptSelect);
        }

        setAttr("pager", pager);
    }

    private void export(ConcurrentHashMap<String, String> searchInfo){
        // List<Record> listExport = Db
        // .find(VnetService.getSelectSql() + " " +
        // VnetService.service.getSqlExceptSelect(searchInfo));

        // PoiRender excel = PoiRender.me(listExport);
        String[] headesExport = VnetService.HEADES_EXPORT;
        String[] columnsExport = VnetService.COLUMNS_EXPORT;

        JSONObject jo = null;
        String name = generateFileName();
        try{
            String exportFileUrl = ExcelLargeDataUtils.exportData(headesExport, columnsExport,
                                                                  VnetService.getSelectSql() + " "
                                                                          + VnetService.service
                                                                                  .getSqlExceptSelect(searchInfo),
                                                                  name, getFilePath(name));
            jo = createDownloadSuccessJSONObject(exportFileUrl);
        }
        catch(IOException e){
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    private JSONObject createDownloadSuccessJSONObject(String exportFileUrl){
        JSONObject jo = new JSONObject();
        jo.put("status", 1);
        jo.put("message", "导出成功，点击下载");
        jo.put("url", exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }

    private JSONObject createDownloadErrorJSONObject(IOException e){
        JSONObject jo = new JSONObject();
        jo.put("status", 0);
        jo.put("message", "导出失败：" + e.getMessage());
        return jo;
    }

    private String getFilePath(String name){
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + name);

        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        logger.debug("cmccbusiness fileDir = " + fileDir);

        if(!StringUtils.isEmpty(fileDir)){
            filePath = fileDir + "/file/" + name;
        }
        return filePath;
    }

    String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String curTime = sdf.format(date);
        String fileName = "V网报表-" + curTime + ".xlsx";
        return fileName;
    }
}
